#include <webx/route.h>
#include <webx/route.h>

class ShareNote : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(ShareNote, "/confile/${filename}")

int ShareNote::process()
{
	param_string(id);
	param_string(dbid);
	param_string(user);
	param_string(flag);
	param_string(title);
	param_string(folder);

	if (id.empty() && title.empty())
	{
		clearResponse();
		
		return XG_PARAMERR;
	}

	webx::CheckSystemRight(this);

	auto getUser = [&](){
		if (user.length() > 0) return user;

		if (token) user = token->getUser();

		return user.empty() ? "system" : user;
	};

	auto getDataId = [&](){
		return token && dbid.empty() ? token->getDataId() : dbid;
	};

	JsonEntity(Result)
	{
		rint(code);
		rint(level);
		rstring(user);
		rstring(title);
		rstring(folder);
		rstring(content);
	};

	Result result;
	sp<DBConnect> dbconn;

	if (id.empty())
	{
		if (folder.empty())
		{
			string sqlcmd = "SELECT USER,LEVEL,CONTENT,FOLDER,TITLE FROM T_XG_CONF WHERE FOLDER='WEBPAGE' AND TITLE=?";

			webx::GetDBConnect(dbid)->select(result, sqlcmd, title);
		}
		else
		{
			
			string sqlcmd = "SELECT USER,LEVEL,CONTENT,FOLDER,TITLE FROM T_XG_CONF WHERE USER=? AND FOLDER=? AND TITLE=?";

			webx::GetDBConnect(getDataId())->select(result, sqlcmd, getUser(), folder, title);
		}
	}
	else
	{
		string sqlcmd = "SELECT USER,LEVEL,CONTENT,FOLDER,TITLE FROM T_XG_CONF WHERE ID=?";

		webx::GetDBConnect(getDataId())->select(result, sqlcmd, id);
	}

	if (result.user.empty()) return XG_NOTFOUND;

	if (flag == "Q")
	{
		result.code = XG_OK;

		out << result.toString();
	}
	else
	{
		if (result.user == getUser() || result.level > 2)
		{
			out << result.content;
		}
	}

	return XG_OK;
}